<template>
  <el-dialog
    :visible="dialogVisible"
    :before-close="handleClose"
    title="盘点入库"
    width="850px"
    append-to-body>

    <div v-loading="loading" v-if="fieldList.length > 0">
      <wk-form
        ref="wkFormBase"
        :model="form"
        :rules="formRules"
        :field-from="form"
        :field-list="fieldList"
        label-position="top" />

      <el-table
        :data="productList"
        :max-height="350"
        style="width: 100%;">
        <template v-for="(field, index) in tableFieldList">
          <el-table-column
            :key="index"
            :prop="field.prop"
            :label="field.label"
            show-overflow-tooltip />
        </template>
        <el-table-column label="本次入库数量">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.inventoryRecordNumber"
              :controls="false"
              :precision="2"
              placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="removeItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer">
      <el-button
        @click="handleClose">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleConfirm">
        确定入库
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
/**
 * Create by yxk at 2020/6/17
 */
import { jxcInventoryRecordAddOrUpdateAPI, jxcInventoryRecordAutomaticAPI } from '@/api/jxc/inventory'
import { userListAPI } from '@/api/common'
import WkForm from '@/components/NewCom/WkForm'

import GenerateRulesMixin from '@/components/NewCom/WkForm/GenerateRules'

export default {
  name: 'EnterDialog',
  components: {
    WkForm
  },
  mixins: [GenerateRulesMixin],
  props: {
    dataList: {
      type: Array,
      default: () => []
    },
    batchId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: true,

      tableFieldList: [
        { prop: 'productName', label: '产品名称' },
        { prop: 'spDataValue', label: '产品规格' },
        { prop: 'productCompany', label: '单位' },
        { prop: 'lossNumber', label: '盈亏数量' },
        { prop: 'weiinventoryRecordNumber', label: '未入库数量' }
      ],
      productList: [],

      fieldList: [],
      form: {
        orderNumber: '',
        inventoryRecordTime: '',
        ownerUserId: '',
        bremark: ''
      },
      formRules: {}
    }
  },
  watch: {
    dataList: {
      handler() {
        const list = this.dataList.map(o => {
          return {
            ...o,
            inventoryRecordNumber: o.weiinventoryRecordNumber,
            remark: ''
          }
        })
        this.productList = list.filter(o => o.weiinventoryRecordNumber !== 0)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.numberRule()
  },
  methods: {
    initForm(flag = false) {
      this.fieldList = []
      this.$nextTick(() => {
        this.fieldList = [
          {
            field: 'orderNumber',
            formType: 'text',
            name: '入库单号',
            placeholder: flag ? '根据编号规则自动生成，支持手动输入' : '',
            isNull: flag ? 0 : 1
          },
          {
            field: 'inventoryRecordTime',
            formType: 'date',
            name: '入库时间',
            isNull: 1
          },
          {
            field: 'ownerUserId',
            formType: 'user',
            name: '负责人',
            request: userListAPI,
            params: { pageType: 0 },
            isNull: 1
          },
          {
            field: 'bremark',
            formType: 'textarea',
            name: '备注'
          }
        ]
        this.fieldList.forEach(item => {
          this.formRules[item.field] = this.getRules(item)
        })
      })
    },
    removeItem(index) {
      this.productList.splice(index, 1)
    },

    handleClose() {
      this.dialogVisible = false
      this.$emit('close')
    },

    numberRule(params = null) {
      return new Promise((resolve, reject) => {
        jxcInventoryRecordAutomaticAPI(params || {}).then(res => {
          if (!params) {
            this.initForm(res.data.states == 1)
          }
          resolve(res.data.repeatState == 0)
        }).catch(() => {
          reject()
        })
      })
    },

    handleConfirm() {
      if (this.loading) return
      this.loading = true
      const instance = this.$refs.wkFormBase.instance

      instance.validate(valid => {
        if (valid) {
          this.loading = false
          if (this.productList.length > 0) {
            for (let i = 0; i < this.productList.length; i++) {
              const item = this.productList[i]
              // if (Math.abs(item.inventoryRecordNumber) > Math.abs(item.weiinventoryRecordNumber)) {
              //   this.$message.error('本次入库数量不能超出对应产品的未入库数量')
              //   return
              // }
              if (item.weiinventoryRecordNumber < 0) {
                if (item.inventoryRecordNumber > 0 || item.inventoryRecordNumber < item.weiinventoryRecordNumber) {
                  this.$message.error('本次入库数量不能超出对应产品的未入库数量')
                  return
                }
              } else {
                if (item.inventoryRecordNumber < 0 || item.inventoryRecordNumber > item.weiinventoryRecordNumber) {
                  this.$message.error('本次入库数量不能超出对应产品的未入库数量')
                  return
                }
              }
            }
            const params = {
              batchId: this.batchId,
              jxcInventoryRecordList: this.productList.map(o => {
                return {
                  ...this.form,
                  batchId: this.batchId,
                  inventoryProductId: o.inventoryProductId,
                  inventoryRecordNumber: o.inventoryRecordNumber,
                  productId: o.productId,
                  remark: o.remark,
                  warehouseId: o.warehouseId
                }
              })
            }
            console.log('save', params)
            this.numberRule({
              value: this.form.orderNumber
            }).then(res => {
              if (!res) {
                this.$message.error('入库单号不能重复')
                return
              }
              console.log('ok---')
              jxcInventoryRecordAddOrUpdateAPI(params).then(() => {
                this.$message.success('操作成功')
                this.loading = false
                this.$emit('update')
                this.handleClose()
              }).catch(() => {
                this.loading = false
              })
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.handleClose()
          }
        } else {
          // 弹出第一个错误
          this.loading = false
          if (instance.fields) {
            for (
              let index = 0;
              index < instance.fields.length;
              index++
            ) {
              const ruleField = instance.fields[index]
              if (ruleField.validateState == 'error') {
                this.$message.error(ruleField.validateMessage)
                break
              }
            }
          }
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

  /deep/ .wk-user-select,
  /deep/ .wk-dep-select {
    margin: 3px 0;
  }
  /deep/ .map_address {
    flex: unset !important;
    width: 100%;
  }

  .el-input-number {
    width: 100%;
    /deep/ .el-input__inner {
      text-align: left;
      padding: 0 8px;
    }
  }
</style>
